package com.free.lit.netapp1;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final static String TAG="YUAN";
    OkHttpClient client = new OkHttpClient();
    TextView tv = null;

    String do_run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.MyShow);
        new Thread(yy_runnable).start();

    }

    Handler yy_handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            Log.d(TAG,"请求结果:\n" + val);
            tv.setText(val);
        }
    };

    Runnable yy_runnable = new Runnable(){
        @Override
        public void run() {
            // TODO: http request.
            String recv_data = null;
            try {
                recv_data = do_run("https://yuanhy0055.github.io/");
                //Log.d(TAG, data);
            } catch (IOException e) {
                recv_data = "<NULL>";
                e.printStackTrace();
            }

            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("value",recv_data);
            msg.setData(data);
            yy_handler.sendMessage(msg);
        }
    };
}
